import {  login } from '@/api/backend/auth';
import { defineStore } from 'pinia'
import {TOKEN_KEY,USER_MENU} from "@/constant/storage.js";
import {getObject, setObject} from "@/api/util/storage.js";
import {getUserMenus} from "@/api/backend/user/menu.js";
import * as storage from "@/api/util/storage.js";
import {ElMessage} from "element-plus";
import {getUserInfo as userInfoRequest} from "@/api/backend/user/user.js";
import userRouteStore from "@/store/modules/route.js";
import {useRouter} from "vue-router";
let useUserStore=defineStore("user",{

    state:()=>{
      return {
          userInfo: getObject(TOKEN_KEY),
          menus: getObject(USER_MENU)
      }
    },
    actions : {
        async userLogin(loginRequest){
            const loginResult = await login(loginRequest)
            if(!loginResult||loginResult.code!==200)return Promise.reject(loginResult)
            this.userInfo=loginResult.data
            setObject(TOKEN_KEY,this.userInfo)
            return loginResult
        },

        async getUserMenu(userId){
            const result = await getUserMenus(userId)
            if(!result||result.code!==200)return Promise.reject(result)
            this.menus=result.data
            setObject(USER_MENU,this.menus)
            return result
        },

        clear(){
            this.userInfo={}
            this.menus=[]
        },
        logout(){
            this.userInfo={}
            this.menus=[]
            storage.clear()
        },

        async getUserInfo(userId){
          const result = await userInfoRequest(userId)
            if(!result||result.code!==200) return Promise.reject(result)
            this.userInfo=result.data
            setObject(TOKEN_KEY,this.userInfo)
            return result
        },
        async prepareUserInfo(){
            const routeStore=userRouteStore()
            const router=useRouter()

            await Promise.all([this.getUserInfo(this.userInfo.userId),routeStore.fetchRoutes(router)])

           const rootRoute=routeStore.routes.filter(item=>item.name==='root')[0]
           this.menus=rootRoute.children
           setObject(USER_MENU,this.menus)

        }
    },
    getters:{}

})

export default useUserStore